package edu.kit.ksri.db.mturk.workerpools;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

import org.apache.log4j.Logger;

import edu.kit.ksri.db.mturk.standaloneutils.OfflinePoolManager.Worker;

/**
 * Copyright (c) 2010-2011 Karlsruhe Institute of Technology (KIT), Germany
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 * 
 * --------------------------------------------------------------------------
 * 
 * Software: CSP/WMV tool for dynamic quality management of microtasks
 * http://www.ksri.kit.edu/Upload/Users/PeopleClouds/HCOMP2011_An_extendable_toolkit_for_managing_quality_of_human-based_eServices.pdf
 * 
 * Organization: Karlsruhe Institute of Technology (KIT), Germany
 * http://www.kit.edu
 * 
 * Project: PeopleClouds project of the Karlsruhe Service Research Institute(KSRI)
 * http://www.ksri.kit.edu/Default.aspx?PageId=818
 * 
 * Contributing authors: David Bermbach, Sandra Rath, Pascal Wichmann, Robert Kern
 */
public class WorkerPool {

	private static Logger basiclog = Logger.getLogger("basic." + WorkerPool.class);
	
	private static final Logger perflog = Logger.getLogger("perf." + WorkerPool.class);

	/** the name of this pool, e.g. active */
	private String poolName = null;

	/** holds references to all the workers of this pool */
	private final HashSet<AbstractWorker> pool = new HashSet<AbstractWorker>();

	/** correctness value in percent. can be used for initializing */
	private double minimumCorrectness = 0;

	/**
	 * 
	 * @param poolName
	 *            the name of the pool which shall be created
	 * @param minimumCorrectness
	 *            minimum correctnes value for this pool. will never be actively
	 *            used by the pool itself.
	 * @throws Exception
	 *             an exception is thrown whenever the newly created pool could
	 *             not be registered with the {@link PoolManager}
	 */
	public static void createNewWorkerPool(String poolName,
			double minimumCorrectness) throws Exception {
		if (!PoolManager.getInstance().registerNewPool(
				new WorkerPool(poolName, minimumCorrectness))) {
			throw new Exception("Name already exists!");
		}
	}

	/**
	 * 
	 * @param poolName
	 *            the name of this pool, e.g. active
	 * @param minimumCorrectness
	 *            minimum correctnes value for this pool. will never be actively
	 *            used by the pool itself.
	 */
	private WorkerPool(String poolName, double minimumCorrectness) {
		this.poolName = poolName;
		this.minimumCorrectness = minimumCorrectness;
		perflog.info("Worker Pool " + poolName + " created.");
	}

	/**
	 * @param e
	 * @return
	 * @see java.util.HashSet#add(java.lang.Object)
	 */
	public boolean addWorker(AbstractWorker e) {
		synchronized (pool) {
			return this.pool.add(e);
		}
	}

	/**
	 * @param c
	 * @return
	 * @see java.util.AbstractCollection#addAll(java.util.Collection)
	 */
	public boolean addWorkers(Collection<AbstractWorker> workers) {
		synchronized (pool) {
			return this.pool.addAll(workers);
		}
	}

	/**
	 * @param o
	 * @return
	 * @see java.util.HashSet#contains(java.lang.Object)
	 */
	public boolean containsWorker(AbstractWorker worker) {
		synchronized (pool) {
			return this.pool.contains(worker);
		}
	}

	/**
	 * @param o
	 * @return
	 * @see java.util.HashSet#remove(java.lang.Object)
	 */
	public boolean removeWorker(AbstractWorker worker) {
		synchronized (pool) {
			return this.pool.remove(worker);
		}
	}

	/**
	 * @param c
	 * @return
	 * @see java.util.AbstractSet#removeAll(java.util.Collection)
	 */
	public boolean removeWorkers(Collection<AbstractWorker> workers) {
		synchronized (pool) {
			return this.pool.removeAll(workers);
		}
	}

	/**
	 * @return
	 * @see java.util.HashSet#size()
	 */
	public int size() {
		synchronized (pool) {
			return this.pool.size();
		}
	}

	/**
	 * @return the poolName
	 */
	public String getPoolName() {
		return this.poolName;
	}

	/**
	 * 
	 * @return whether this pool is registered with the {@link PoolManager}
	 */
	public boolean isRegisteredPool() {
		return PoolManager.getInstance().containsWorkerPool(poolName);
	}

	/**
	 * 
	 * @param level
	 *            correctness level
	 * @return a set of all workers from this pool that have a correctness level
	 *         higher than level
	 */
	public HashSet<AbstractWorker> getWorkersWithCorrectnessHigherThan(double level) {
		HashSet<AbstractWorker> res = new HashSet<AbstractWorker>();
		synchronized (pool) {
			for (AbstractWorker w : pool) {
				if (w.getCorrectnessLevel() > level) {
					res.add(w);
				}
			}
		}
		return res;
	}

	/**
	 * 
	 * @param numberOfWorkers
	 *            the number of workers
	 * @return a set of all workers from this pool containing the specified
	 *         number of workers (or less if the pool's size is smaller)
	 *         starting with the best one.
	 */
	public HashSet<AbstractWorker> getBestWorkers(int numberOfWorkers) {
		HashSet<AbstractWorker> res = new HashSet<AbstractWorker>();
		if (numberOfWorkers <= 0)
			return res;
		if (numberOfWorkers >= size()) {
			synchronized (pool) {
				res.addAll(pool);
				return res;
			}
			// not the entire pool is needed
		}
		synchronized (pool) {
			AbstractWorker[] temp = new AbstractWorker[pool.size()];
			int i = 0;
			for (AbstractWorker w : pool) {
				temp[i++] = w;
			}
			Arrays.sort(temp);
			for (i = 0; i < numberOfWorkers; i++) {
				res.add(temp[i]);
			}
		}
		return res;
	}

	/**
	 * 
	 * @return a list of all the worker IDs managed within this pool.
	 */
	public List<String> getWorkerList() {
		ArrayList<String> res = new ArrayList<String>();
		synchronized (pool) {
			for (AbstractWorker w : pool)
				res.add(w.getWorkerId());
		}
		return res;
	}

	/**
	 * transforms each {@link Worker}'s toStringArray() result into a 2D String
	 * array.
	 * 
	 * @return
	 */
	public String[][] getWorkerArray() {
		String[][] res;
		synchronized (pool) {
			res = new String[pool.size() + 2][0];
			res[0] = new String[2];
			res[0][0] = "Pool Name";
			res[0][1] = "" + poolName;
			res[1] = new String[2];
			res[1][0] = "# of Workers";
			res[1][1] = "" + pool.size();
			int counter = 2;
			for (AbstractWorker w : pool)
				res[counter++] = w.toStringArray();

		}
		return res;
	}

	/**
	 * retrieves a worker object from the list of workers. be careful with
	 * changes
	 * 
	 * @param id
	 *            the worker id
	 * @return the object or null if an error occurred or the specified worker
	 *         does not exist.
	 */
	public AbstractWorker getWorkerForID(String id) {
		if (id == null) {
			basiclog.warn("ID must not be null.");
			return null;
		}
		synchronized (pool) {
			for (AbstractWorker w : pool) {
				if (w.getWorkerId().equals(id)) {
					return w;
				}
			}
		}
		return null;
	}

	/**
	 * returns the complete list of {@link Worker} objects from this pool. be
	 * careful with changes.
	 * 
	 * @return
	 */
	public List<AbstractWorker> getWorkers() {
		ArrayList<AbstractWorker> l = new ArrayList<AbstractWorker>();
		synchronized (pool) {
			l.addAll(pool);
		}
		return l;
	}

	/**
	 * 
	 * @see java.util.HashSet#clear()
	 */
	public void clear() {
		synchronized (pool) {
			this.pool.clear();
		}
	}

	/**
	 * @return the minimumCorrectness
	 */
	public double getMinimumCorrectness() {
		return this.minimumCorrectness;
	}

	/**
	 * @param minimumCorrectness
	 *            the minimumCorrectness to set
	 */
	public void setMinimumCorrectness(double minimumCorrectness) {
		this.minimumCorrectness = minimumCorrectness;
	}

}
